package org.springcloud.wisdom.amusement.service.serviceimp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springcloud.wisdom.amusement.controller.notice.controller.Page;
import org.springcloud.wisdom.amusement.dao.TeamRecordsDao;
import org.springcloud.wisdom.amusement.dao.Team_StudentDao;
import org.springcloud.wisdom.amusement.entity.AmusementNotice;
import org.springcloud.wisdom.amusement.entity.Student;
import org.springcloud.wisdom.amusement.entity.TeamRecordsEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TeamRecordsService {
    @Autowired
    private TeamRecordsDao recordsDao;
    @Autowired
    private Team_StudentDao teamStudentDao;

    private static final Logger logger = LoggerFactory.getLogger(TeamRecordsService.class);
    // 辅助方法，生成随机签到ID

    // 辅助方法，获取当前日期和时间，格式化为"yyyy-MM-dd HH:mm:ss"
    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    // 发起签到并处理考勤记录
    public boolean insertRecordsAndAttendence(Integer teamid, Integer nid) {
        // 获取某门课程的所有学生
        List<Student> students = teamStudentDao.selectStudent(teamid);
        if (students == null || students.isEmpty()) {
            return false;
        }


        for (Student student : students) {
            // 为每个学生生成签到记录
            String signTime = getCurrentDateTime();
            TeamRecordsEntity recordsEntity = new TeamRecordsEntity();
            recordsEntity.setTeamid(teamid);
            recordsEntity.setNid(nid);
            recordsEntity.setSid(student.getSid());
            recordsEntity.setStu(false); // 默认stu为false，表示未签到
            recordsEntity.setSigntime(signTime);

            // 插入签到记录
            if (recordsDao.insertRecords(recordsEntity) <= 0) {
                return false; // 如果插入失败，则返回false
            }

//            // 检查并可能插入或更新考勤记录
//            AttendenceEntity attendence = attendenceDao.selectByCidAndSid(cid, student.getSid());
//            if (attendence == null) {
//                AttendenceEntity newAttendence = new AttendenceEntity();
//                newAttendence.setCid(cid);
//                newAttendence.setSid(student.getSid());
//                newAttendence.setChour(chour);
//                newAttendence.setCount("1");
//                newAttendence.setSigncount("0");
//                attendenceDao.insertAttendence(newAttendence);
//            } else {
//                attendence.setCount(String.valueOf(Integer.parseInt(attendence.getCount()) + 1));
//                attendenceDao.updateAttendence(attendence);
//            }
//        }
        }
            return true;
    }

    //签到并更新考勤
    public boolean updateRecordStatus(TeamRecordsEntity recordsEntity) {
        if (recordsEntity == null || recordsEntity.getId() == null) {
            return false;
        }

        try {
            // 更新签到状态
            recordsEntity.setStu(true);
            String reactTime = getCurrentDateTime();
            recordsEntity.setReacttime(reactTime);
            recordsDao.updateRecords(recordsEntity);

            // 获取考勤记录
//            AttendenceEntity attendence = attendenceDao.selectByCidAndSid(recordsEntity.getCid(), recordsEntity.getSid());
//            logger.info("Before signcount update, attendence: {}", attendence); // 记录更新前的signcount
//
//            if (attendence != null) {
//                int signcount = attendence.getSigncount() != null ? Integer.parseInt(attendence.getSigncount()) : 0;
//                attendence.setSigncount(String.valueOf(++signcount));
//                attendenceDao.updateAttendence(attendence);
//                // 再次更新signcount，确保原子性
//                attendenceDao.updateSigncountByCidAndSid(recordsEntity.getCid(), recordsEntity.getSid());
//            }
//
//            logger.info("After signcount update, attendence: {}", attendence); // 记录更新后的signcount

            return true;
        }catch (Exception e) {
            logger.error("Error updating signcount", e); // 记录异常信息
            return false;
        }
    }

    // 获取学生个人签到记录的分页数据
    public Page<TeamRecordsEntity> getAllRecords(int pageNum, int pageSize, String sid) {
        int start = (pageNum - 1) * pageSize;
        List<TeamRecordsEntity> list = recordsDao.get(sid, start, pageSize);
        int total = recordsDao.Counts(sid);
        int pages = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
        Page<TeamRecordsEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(total);
        page.setPages(pages);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return page;
    }

    // 获取一个活动所有签到记录的分页数据
    public Page<TeamRecordsEntity> getAllRecords2(int pageNum, int pageSize, Integer nid) {
        int start = (pageNum - 1) * pageSize;
        List<TeamRecordsEntity> list = recordsDao.get2(nid, start, pageSize);
        int total = recordsDao.Counts2(nid);
        int pages = (int) (total % pageSize == 0 ? total / pageSize : total / pageSize + 1);
        Page<TeamRecordsEntity> page = new Page<>();
        page.setRecords(list);
        page.setTotal(total);
        page.setPages(pages);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return page;
    }
    //获取签到结果
    public List<TeamRecordsEntity> getActiveCheckResult(Integer nid,Integer teamid) {
        List<TeamRecordsEntity> list = new ArrayList<>();
        TeamRecordsEntity teamRecordsEntity = new TeamRecordsEntity();
        teamRecordsEntity.setShouldarrive(recordsDao.CountsShoudArrive(nid, teamid));
        teamRecordsEntity.setTruearrive(recordsDao.CountsTureArrive(nid, teamid));
        teamRecordsEntity.setSigntime(recordsDao.getTimeResult(nid, teamid));
        teamRecordsEntity.setTitle(recordsDao.getTitleResult(nid, teamid));
        list.add(teamRecordsEntity);
        return list;
    }
    //获取签到结果
    public List<Student> getUnArriveStudent(Integer nid,Integer teamid) {
        return recordsDao.getUnArriveStudent(nid,teamid);
    }
    //获取公告列表
    public List<AmusementNotice>  getTeamNotice(Integer type){
        return recordsDao.getTeamNotice(type);
    }
}